#include "mytcpsocket.h"
#include <QDebug>

MyTcpSocket::MyTcpSocket(QObject *parent)
    : QTcpSocket{parent}
{
    connect(this, SIGNAL(readyRead()), this, SLOT(recvMsg()));
    connect(this, SIGNAL(disconnected()), this, SLOT(clientOffline()));
}

QString MyTcpSocket::getName()
{
    return m_strName;
}

void MyTcpSocket::recvMsg()
{
    qDebug() << this->bytesAvailable();
    uint uiPDULen = 0;

    this->read((char*)&uiPDULen, sizeof(uint));
    uint uiMsgLen = uiPDULen - sizeof(PDU);

    PDU *pdu = mkPDU(uiMsgLen);
    PDU *respdu = mkPDU(0);
    this->read((char*)pdu + sizeof(uint), uiPDULen - sizeof(uint));

    switch(pdu->uiMsgType)
    {
    case ENUM_MSG_TYPE_REGIST_REQUEST:
    {
        char caName[32] = {'\0'};
        char caPwd[32] = {'\0'};
        strncpy(caName, pdu->caData, 32);
        strncpy(caPwd, pdu->caData + 32, 32);
        bool ret = OpeDB::getInstance().handleRegist(caName, caPwd);
        respdu->uiMsgType = ENUM_MSG_TYPE_REGIST_RESPOND;
        if(ret)
        {
            strcpy(respdu->caData, REGIST_OK);
        }
        else
        {
            strcpy(respdu->caData, REGIsT_FAILED);
        }
        write((char*)respdu, respdu->uiPDULen);

        break;
    }
    case ENUM_MSG_TYPE_LOGIN_REQUEST:
    {
        char caName[32] = {'\0'};
        char caPwd[32] = {'\0'};

        strncpy(caName, pdu->caData, 32);
        strncpy(caPwd, pdu->caData + 32, 32);

        bool ret = OpeDB::getInstance().handleLogin(caName, caPwd);
        respdu->uiMsgType = ENUM_MSG_TYPE_LOGIN_RESPOND;
        if(ret)
        {
            strcpy(respdu->caData, LOGIN_OK);
            m_strName = caName;
        }
        else
        {
            strcpy(respdu->caData, LOGIN_FAILED);
        }
        write((char*)respdu, respdu->uiPDULen);

        break;
    }
    case ENUM_MSG_TYPE_CANCEl_REQUEST:
    {
        char caName[32] = {'\0'};
        char caPwd[32] = {'\0'};

        strncpy(caName, pdu->caData, 32);
        strncpy(caPwd, pdu->caData + 32, 32);

        bool ret = OpeDB::getInstance().handleCancel(caName, caPwd);
        respdu->uiMsgType = ENUM_MSG_TYPE_CANCEL_RESPOND;
        if(ret)
        {
            strcpy(respdu->caData, CANCEL_OK);
        }
        else
        {
            strcpy(respdu->caData, CANCEL_FAILED);
        }
        write((char*)respdu, respdu->uiPDULen);

        break;
    }
    default:
        break;
    }

    // qDebug() << "caName:" << caName << "caPwd:" << caPwd;
    //qDebug() << pdu->uiMsgType << (char*)(pdu->caMsg);

    free(respdu);
    respdu = NULL;
    free(pdu);
    pdu = NULL;
}

void MyTcpSocket::clientOffline()
{
    OpeDB::getInstance().handleOffline(m_strName.toStdString().c_str());
    emit offline(this);
}


